package com.yuerlive.rainbow.widget;

import android.animation.Animator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.common.AppConfig;
import com.yuerlive.rainbow.entity.GradleInfo;
import com.yuerlive.rainbow.entity.LiveInfo;
import com.yuerlive.rainbow.entity.SpecialGift;
import com.yuerlive.rainbow.module.game.FragmentGameNiuniu;
import com.yuerlive.rainbow.module.live.LiveRoomActivity;
import com.yuerlive.rainbow.module.live.fragment.FragmentChatRoom;
import com.yuerlive.rainbow.observer.Observerable;
import com.yuerlive.rainbow.observer.ObserverableType;
import com.yuerlive.rainbow.utils.DeviceUtils;
import com.yuerlive.rainbow.utils.GlideUtil;
import com.yuerlive.rainbow.utils.L;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by Admin on 2017/5/25.
 */

public class PiaoPingView extends RelativeLayout {
    private static final String TAG = "PiaoPingView";
    private Context mContext;
    private int mScreenWidth;
    private List<View> mChildList;
    private boolean isFirst = true;
    private Timer timer = new Timer();
    private TimerTask giftTask = new GiftTask(this);
    private Queue<SpecialGift> msgQueue = new LinkedBlockingDeque();
    private boolean mIsWorking = false;

    public enum XCAction {
        SHOW, HIDE
    }

    public static enum XCDirection {
        FROM_RIGHT_TO_LEFT,
        FORM_LEFT_TO_RIGHT
    }

    private XCDirection mDirection = XCDirection.FROM_RIGHT_TO_LEFT;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            final int pos = msg.what;
            switch (pos) {
                case 0:
                    ViewPropertyAnimator animator;
                    if (mDirection == XCDirection.FROM_RIGHT_TO_LEFT) {
                        animator = mChildList.get(msg.what).animate()
                                .translationXBy(-(mScreenWidth + mChildList.get(msg.what).getWidth()));
                    } else {
                        animator = mChildList.get(msg.what).animate()
                                .translationXBy(mScreenWidth + mChildList.get(msg.what).getWidth());
                    }
                    animator.setDuration(8000);
                    animator.setInterpolator(new LinearInterpolator());
                    animator.setListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animator) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animator) {
                            PiaoPingView.this.removeView(mChildList.get(pos));
                            mChildList.remove(mChildList.get(pos));
                            animator.removeAllListeners();
                            animator = null;
                        }

                        @Override
                        public void onAnimationCancel(Animator animator) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animator) {

                        }
                    });
                    animator.start();
                    break;
                case 1:
                    if (mChildList.size() <= 0) {
                        SpecialGift gift = msgQueue.poll();
                        createDanmuView(gift);
                        mHandler.sendEmptyMessage(0);
                    }
                    break;
            }
        }
    };

    public PiaoPingView(Context context) {
        this(context, null, 0);
    }

    public PiaoPingView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PiaoPingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();

    }

    private void init() {
        mScreenWidth = DeviceUtils.deviceWidth(mContext);
        mChildList = new ArrayList<>();
    }

    public void add(SpecialGift giftAttachment) {
        msgQueue.add(giftAttachment);
    }

    public void start() {
        switchAnimation(XCAction.SHOW);
        if (isFirst) {
            timer.schedule(giftTask, 1000, 1000);
        }
        mIsWorking = true;
    }

    public void hide() {
        switchAnimation(XCAction.HIDE);
        mIsWorking = false;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        int childCount = this.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view = getChildAt(i);
            RelativeLayout.LayoutParams lp = (LayoutParams) view.getLayoutParams();
            if (lp.leftMargin <= 0) {
                if (mDirection == XCDirection.FORM_LEFT_TO_RIGHT) {
                    view.layout(-view.getMeasuredWidth(), lp.topMargin,
                            0, lp.topMargin + view.getMeasuredHeight());
                } else {
                    view.layout(mScreenWidth, lp.topMargin, mScreenWidth + view.getMeasuredWidth(),
                            lp.topMargin + view.getMeasuredHeight());
                }

            } else {
                continue;
            }
        }
    }

    private void switchAnimation(final XCAction action) {
        if (action == XCAction.HIDE) {
            PiaoPingView.this.setVisibility(View.GONE);
        } else {
            PiaoPingView.this.setVisibility(View.VISIBLE);
        }
    }

    /*
        type =1  普通礼物  2 全平台通知 3 用户进入房间
     */
    public void createDanmuView(final SpecialGift gift) {
        View layout = null;
        TextView tvContent = null;
        if (gift.getType() == FragmentChatRoom.COMMON_PIAO_PING_VIEW) {
            layout = LayoutInflater.from(getContext()).inflate(R.layout.layout_danmu_special, null);
            CircleImageView civHeader = (CircleImageView) layout.findViewById(R.id.civHeader);
            //设置发送者的头像
            GlideUtil.load(mContext, gift.getSenderIcon(), civHeader);
            TextView tvName = (TextView) layout.findViewById(R.id.tvName);
            tvName.setText(gift.getFrom());
            ImageView ivPic = (ImageView) layout.findViewById(R.id.ivPic);
            ivPic.setVisibility(View.VISIBLE);
            //TODO 设置礼物图片
            GlideUtil.load(mContext, gift.getGiftIcon(), ivPic);
            tvContent = (TextView) layout.findViewById(R.id.tvContent);
            tvContent.setText("送出了" + gift.getGiftName());
        } else if (gift.getType() == FragmentChatRoom.MEMBER_IN) {
            layout = LayoutInflater.from(getContext()).inflate(R.layout.layout_danmu_special2, null);
            tvContent = (TextView) layout.findViewById(R.id.tvContent);
            tvContent.setText(Html.fromHtml(getResources().getString(R.string.piaoping_content, String.valueOf(gift.getUserLevel()), gift.getFrom())));
        } else if (gift.getType() == FragmentChatRoom.NOTICE_PIAO_PING_VIEW) {
            layout = LayoutInflater.from(getContext()).inflate(R.layout.layout_danmu_special2, null);
            tvContent = (TextView) layout.findViewById(R.id.tvContent);
            if (gift != null && gift.getAllPlatformData() != null) {
                if (gift.getAllPlatformData().getAllPlatformNoticeType() == 1) {
                    tvContent.setText(Html.fromHtml(getResources().getString(R.string.piaoping_content2, gift.getAllPlatformData().getSenderName(), gift.getAllPlatformData().getGiftName())));
                } else {
                    tvContent.setText(Html.fromHtml(getResources().getString(R.string.piaoping_content3, gift.getAllPlatformData().getWinnerName(), gift.getAllPlatformData().getWinSweetNum())));
                }
            }
        }
        HorizontalScrollView hsView = (HorizontalScrollView) layout.findViewById(R.id.hsView);
        LinearLayout.MarginLayoutParams layoutParams = (LinearLayout.MarginLayoutParams) hsView.getLayoutParams();
        RelativeLayout.LayoutParams lp = new LayoutParams(3600,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(Gravity.CENTER_VERTICAL);
        layout.setLayoutParams(lp);
        this.addView(layout);
        mChildList.add(layout);
        tvContent.setClickable(true);
        tvContent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mContext instanceof LiveRoomActivity && gift.getType() == FragmentChatRoom.NOTICE_PIAO_PING_VIEW
                        && !gift.getAllPlatformData().getChatroomId().equals(((LiveRoomActivity) mContext).getChatRoomId())) {

                    if (((LiveRoomActivity) mContext).isBanker) {
                        ((LiveRoomActivity) mContext).showSnackbar(
                                BaseActivity.getRootView((Activity) mContext),
                                "您是庄家，下庄前不能进入其他房间"
                                ,0
                        );
                    } else if (((LiveRoomActivity) mContext).hasDeal) {
                        ((LiveRoomActivity) mContext).showSnackbar(
                                BaseActivity.getRootView((Activity) mContext),
                                "您已下注，本局游戏结算前不能进入其他房间"
                                ,0
                        );
                    } else {
                        AppConfig.isJumpFromLive = true;
                        ((LiveRoomActivity)mContext).finish();
                        Observerable.getInstance().notifyChange(ObserverableType.EXITLIVEROOM,1);
                        Intent i = new Intent();
                        i.setClass(mContext, LiveRoomActivity.class);
                        i.putExtra("liveId", gift.getAllPlatformData().getLiveId());
                        i.putExtra("chatroomId", gift.getAllPlatformData().getChatroomId());
                        i.putExtra("flag", "liveroom");

                        mContext.startActivity(i);
                    }

                }
            }
        });
    }

    public void release() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (giftTask != null) {
            giftTask.cancel();
            giftTask = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    private static class GiftTask extends TimerTask {
        private WeakReference<PiaoPingView> reference;

        public GiftTask(PiaoPingView reference) {
            this.reference = new WeakReference<PiaoPingView>(reference);
        }

        @Override
        public void run() {
            if (reference.get() != null && reference.get().msgQueue.size() > 0) {
                reference.get().mHandler.sendEmptyMessage(1);
            }
        }
    }
}
